<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class MFilePostController
    extends MApplicationComponent 
    implements MIController
{
    
    public function invoke($uri=null)
    {
                                parent::init();
        
        $url_manager = new MUrlManager();
        $root = $url_manager->parseRootFromUrl($uri);
        if ($root == false) {
            throw new MFilesException(FXP::t(MConst::PATH_ERROR), MConst::HTTP_CODE_411);;
        }
                                
        $create_handler = MFilesCommon::initMFilesCommon();
        if (count($_FILES) == 0) {
            throw new MFilesException(FXP::t(MConst::PARAMS_ERROR), MConst::HTTP_CODE_400);
        }
        
        $keys = array_keys($_FILES);
        if (count($keys) != 1) {
            throw new MFilesException(FXP::t(MConst::PARAMS_ERROR), MConst::HTTP_CODE_400);
        }
        $key = $keys[0];
                                if (isset($_FILES[$key]) === false)
        {
            throw new MFilesException(FXP::t(MConst::PARAMS_ERROR), MConst::HTTP_CODE_400);
        }
                                if ($_FILES[$key]["error"] != 0) {
            throw new MFilesException(FXP::t(MConst::PARAMS_ERROR), MConst::HTTP_CODE_400);
        }
        
        $file_name = $_FILES[$key]["name"];
        $type      = $_FILES[$key]["type"];
        $size      = $_FILES[$key]["size"];
        $tmp_name  = $_FILES[$key]["tmp_name"];
                                if (file_exists($tmp_name) === false) {
            throw new MFilesException(FXP::t(MConst::INTERNAL_SERVER_ERROR), MConst::HTTP_CODE_500);
        }
        
                                if (filesize($tmp_name) != $size) {
            throw new MFilesException(FXP::t("The file upload error!"), MConst::HTTP_CODE_400);
        }
        
        $signature = MUtils::getFileSha1($tmp_name);
                                $parent_path = "/" . $url_manager->parsePathFromUrl($uri);
        $path        = $parent_path . "/" . $file_name;

        $create_handler->size           = $size;
        $create_handler->parent_path    = MUtils::convertStandardPath($parent_path);
        $create_handler->file_name      = $file_name;
        $create_handler->root           = $root;
        $create_handler->path           = MUtils::convertStandardPath($path);;
        $create_handler->type           = $type;
        
                $create_handler->saveFile($tmp_name, $signature, $size);
                                $create_handler->SaveFileDetails();
        $create_handler->buildResult();
    }
    
    
    
    
    public function handleException($exception)
    {
        parent::displayException($exception);
    }
}
?>
